package com.siyoumi.app.modules.act.web;

import com.siyoumi.app.entity.ActData;
import com.siyoumi.app.entity.ActSet;
import com.siyoumi.app.entity.SysPrizeSet;
import com.siyoumi.app.modules.act.service.SvcActSet;
import com.siyoumi.app.service.ActDataService;
import com.siyoumi.component.XApp;
import com.siyoumi.component.XRedis;
import com.siyoumi.component.http.XHttpContext;
import com.siyoumi.exception.EnumSys;
import com.siyoumi.mybatispuls.JoinWrapperPlus;
import com.siyoumi.util.XDate;
import com.siyoumi.util.XReturn;
import com.siyoumi.util.XStr;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

//卜蜂莲花-大转盘
@RestController
@RequestMapping("/wxapp/act/cplotus")
public class ApiCplotus
        extends ActApiBase {
    private String redisKeyUv(String actId) {
        return XStr.concat("act:", actId, "|uv");
    }

    /**
     * 初始化
     */
    @GetMapping("init")
    public XReturn init() {
        ActSet entityActSet = getActSet();

        //奖品
        List<SysPrizeSet> listPrize = SvcActSet.getBean().listPrize(entityActSet.getKey());
        List<Map<String, Object>> listPrizeMap = listPrize.stream().map(item -> {
            Map<String, Object> data = new HashMap<>();
            data.put("pset_id", item.getKey());
            data.put("pset_name", item.getPset_name());
            data.put("pset_pic", item.getPset_pic());
            data.put("pset_str_00", item.getPset_str_00());
            return data;
        }).collect(Collectors.toList());

        getR().setData("act", entityActSet);
        getR().setData("list_prize", listPrizeMap);

        //剩余抽奖机会
        getR().setData("chou_left", getLeftChou());
        //附加参数
        getR().setData("append_data", SvcActSet.getBean().getAppendData(entityActSet.getKey()));

        String beginStr = XDate.format(entityActSet.getAset_begin_date(), "yyMMdd");
        String endStr = XDate.format(entityActSet.getAset_end_date(), "yyMMdd");
        getR().setData("b", beginStr);
        getR().setData("e", endStr);

        //参与人数
        getR().setData("uv", getUv());

        return getR();
    }

    /**
     * 增加抽奖机会
     */
    @GetMapping("add_chou")
    public XReturn addChou() {
        String code = input("code");
        if (XStr.isNullOrEmpty(code)) {
            return EnumSys.MISS_VAL.getR("缺少小票");
        }

        boolean passCheck = false;
        if ("999".equals(code)) {
//            passCheck = true;
        }

        ActSet entityActSet = getActSet();

        if (!passCheck) {
            Integer ActBeginInt = XStr.toInt(XDate.format(entityActSet.getAset_begin_date(), "yyMMdd"));
            Integer ActEndInt = XStr.toInt(XDate.format(entityActSet.getAset_end_date(), "yyMMdd"));
            // 2212060140100190019
            // 221206
            Integer codeDate = XStr.toInt(XStr.maxLen(code, 6));
            if (codeDate >= ActBeginInt && codeDate <= ActEndInt) {
                //pass
            } else {
                XReturn r = EnumSys.ERR_VAL.getR("小票日期非法：" + codeDate);
                r.setData("act_begin", ActBeginInt);
                r.setData("act_end", ActEndInt);
                return r;
            }
        }


        ActDataService appData = ActDataService.getBean();

        String key = "add|" + code;
        if (passCheck) {
            key = "add|999" + XApp.getStrID();
        }

        ActData entityData = appData.getEntity(entityActSet.getKey(), key);
        if (entityData != null) {
            return XReturn.getR(20045, "小票已存在");
        }

        Map<String, String> appendData = SvcActSet.getBean().getAppendData(entityActSet.getKey());
        Integer chouCountMax = XStr.toInt(appendData.get("chou_count_max"), 0);
        Long addTotal = getAddTotal();
        if (addTotal >= chouCountMax) {
            return XReturn.getR(20046, "添加抽奖机会已到达上限" + chouCountMax);
        }


        //添加机会
        entityData = new ActData();
        entityData.setAdata_x_id(XHttpContext.getX());
        entityData.setAdata_actset_id(entityActSet.getKey());
        entityData.setAdata_openid(getOpenid());
        entityData.setAdata_uix(key);
        entityData.setAdata_str_00(code);
        entityData.setAutoID();
        appData.save(entityData);

        //清参与人数缓存
        XRedis.getBean().del(redisKeyUv(getActId()));

        getR().setData("entity_data", entityData);
        getR().setData("code", code);

        return getR();
    }

    /**
     * 抽奖
     */
    @GetMapping("chou")
    public XReturn chou() {
        ActSet entityActSet = getActSet();

        ActDataService appData = ActDataService.getBean();
        JoinWrapperPlus<ActData> query = queryLeftChou();
        ActData entityAdd = appData.first(query);
        if (entityAdd == null) {
            return XReturn.getR(20123, "抽奖机会已用光");
        }

        return XApp.getTransaction().execute(status -> {
            XReturn r = SvcActSet.getBean().chouLock(entityActSet.getKey(), entityAdd.getKey());

            //标记已使用
            ActData entityAddUpdate = new ActData();
            entityAddUpdate.setAdata_id(entityAdd.getKey());
            entityAddUpdate.setAdata_int_00(1);
            appData.updateById(entityAddUpdate);

            return r;
        });
    }


    public JoinWrapperPlus<ActData> queryLeftChou() {
        ActDataService appData = ActDataService.getBean();
        JoinWrapperPlus<ActData> query = appData.listQuery(getActId(), getOpenid());
        query.eq("adata_int_00", 0)
                .likeRight("adata_uix", "add|");
        return query;
    }

    /**
     * 添加抽奖机会-总数
     */
    public Long getAddTotal() {
        ActDataService appData = ActDataService.getBean();
        JoinWrapperPlus<ActData> query = appData.listQuery(getActId(), getOpenid());
        query.likeRight("adata_uix", "add|");

        return appData.count(query);
    }

    /**
     * 剩余抽奖机会
     */
    public Long getLeftChou() {
        ActDataService appData = ActDataService.getBean();
        JoinWrapperPlus<ActData> query = queryLeftChou();

        return appData.count(query);
    }

    /**
     * 人数
     */
    public Long getUv() {
        String key = redisKeyUv(getActId());
        if (XRedis.getBean().exists(key)) {
            return XStr.toLong(XRedis.getBean().get(key));
        }

        ActDataService appData = ActDataService.getBean();
        JoinWrapperPlus<ActData> query = appData.listQuery(getActId(), getOpenid());
        query.likeRight("adata_uix", "add|");
        query.select(XStr.concat("COUNT(DISTINCT adata_openid) AS total"));
        Map<String, Object> map = appData.firstMap(query);
        Long uv = (Long) map.get("total");

        XRedis.getBean().setEx(key, uv.toString(), 3600);

        return uv;
    }
}
